// src/router/menu.js
import { getMenus } from "@/api/menu"
import router from "@/router"

const dynamicRouteNames = []

// 递归收集所有路由的 name
function collectRouteNames(route, nameList) {
  if (route.name) nameList.push(route.name)
  if (route.children && route.children.length > 0) {
    route.children.forEach(child => collectRouteNames(child, nameList))
  }
}

export async function loadAsyncRoutes(role) {
  const res = await getMenus(role)
  const menuData = res.data.data || []

  clearDynamicRoutes()

  const asyncRoutes = menuData.map(item => {
    const route = {
      path: item.path,
      name: item.name,
      meta: {
        title: item.title,
        icon: item.icon,
        top: item.top
      },
      children: []
    }

    if (item.childMenus && item.childMenus.length > 0) {
      route.component = () => import('@/layout/Layout.vue')
      route.children = item.childMenus.map(child => {
        const childRoute = {
          path: child.path,
          name: child.name,
          meta: {
            title: child.title,
            icon: child.icon
          },
          component: () => import(`@/views/${item.name}/${child.component}.vue`)
        }
        return childRoute
      })
    } else {
      route.component = () => import(`@/views/${item.name}/${item.component}.vue`)
    }

    // ⚠️ 递归收集所有的 name（包括子路由）
    collectRouteNames(route, dynamicRouteNames)

    return route
  })

  asyncRoutes.forEach(route => {
    router.addRoute('home', route)
  })
}

export function clearDynamicRoutes() {
  dynamicRouteNames.forEach(name => {
    if (router.hasRoute(name)) {
      router.removeRoute(name)
    }
  })
  dynamicRouteNames.length = 0
}
